package com.gdpu.project.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gdpu.page.vo.QueryResult;
import com.gdpu.project.dao.CgTreatiseDao;
import com.gdpu.project.vo.CgConference;
import com.gdpu.project.vo.CgProject;
import com.gdpu.project.vo.CgThesis;
import com.gdpu.project.vo.CgTreatise;


public class CgTreatiseDaoImpl extends HibernateDaoSupport implements CgTreatiseDao {
	private static final Log log = LogFactory.getLog(CgTreatiseDaoImpl.class);
	// property constants
	public static final String TREATISE_ID = "treatiseId";
	public static final String TEACHER_ID = "teacherId";
	public static final String TREATISE_TITLE = "treatiseTitle";
	public static final String PUBLISH_ADRESS = "publishAdress";
	public static final String PUBLISH_DW = "publishDw";
	public static final String TREATISE_TYPE = "treatiseType";
	public static final String ZI_SHU = "ziShu";
	public static final String LANGUAGE = "language";
	public static final String YI_WEN = "yiWen";
	public static final String XUE_KE = "xueKe";
	public static final String SCHOOL_SIGN = "schoolSign";
	public static final String ISBN = "isbn";
	public static final String KE_YAN_FEN = "keYanFen";
	public static final String COMMENT = "comment";

	protected void initDao() {
		// do nothing
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#save(com.gdpu.project.vo.CgTreatise)
	 */
	public void save(CgTreatise transientInstance) {
		log.debug("saving CgTreatise instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#delete(com.gdpu.project.vo.CgTreatise)
	 */
	public void delete(CgTreatise persistentInstance) {
		log.debug("deleting CgTreatise instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findById(java.lang.Integer)
	 */
	public CgTreatise findById(java.lang.Integer id) {
		log.debug("getting CgTreatise instance with id: " + id);
		try {
			CgTreatise instance = (CgTreatise) getHibernateTemplate().get(
					"com.gdpu.project.vo.CgTreatise", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByExample(com.gdpu.project.vo.CgTreatise)
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<CgTreatise> findByExample(CgTreatise instance,int firstindex,int maxresult) {
		log.debug("finding CgTreatise instance by example");
		try {
			List<CgTreatise> results = getHibernateTemplate().findByExample(instance);
			int count=results.size();
			if(firstindex!=-1&&maxresult!=-1){
				results=results.subList(firstindex, firstindex+maxresult-1);
			}
			QueryResult<CgTreatise> queryResult=new QueryResult<CgTreatise>();
			queryResult.setResultlist(results);
			queryResult.setTotalrecord(count);
			log.debug("find by example successful, result size: "
					+ results.size());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByProperty(java.lang.String, java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByProperty(String propertyName, Object value,int firstindex,int maxresult) {
		log.debug("finding CgTreatise instance with property: " + propertyName
				+ ", value: " + value);
		try {
			QueryResult<CgTreatise> queryResult=new QueryResult<CgTreatise>();
			Session session=getSessionFactory().getCurrentSession();
			Query query1=session.createQuery("from CgTreatise as model where model."
					+ propertyName + " like :propertyName");
			Query query2=session.createQuery("select count(*) from CgTreatise as model where model."
					+ propertyName + " like :propertyName");
			if(value!=null){
				query1.setParameter("propertyName", value);
				query2.setParameter("propertyName", value);
			}else{
				query1.setParameter("propertyName", "%%");
				query2.setParameter("propertyName", "%%");
				
			}
			if(firstindex!=-1&&maxresult!=-1){
				query1.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			queryResult.setResultlist(query1.list());
			queryResult.setTotalrecord((Long)query2.uniqueResult());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	@SuppressWarnings("unchecked")
	public List<CgTreatise> nfindByProperty(String propertyName, String value,Date begin,Date end) {
		log.debug("finding CgTreatise instance with property: " + propertyName
				+ ", value: " + value);
		try {
			StringBuilder builder=new StringBuilder();
			String queryString = "from CgTreatise as model where model."
				+ propertyName + "= ?";
			builder.append(queryString);
			if(begin!=null){
				builder.append(" and model.publishDate>=? ");
			}
			if(end!=null){
				builder.append(" and model.publishDate<=? ");
			}
			List<Object> pramList=new ArrayList<Object>();
			if(value!=null){
				pramList.add(value);
			}
			if(begin!=null){
				pramList.add(begin);
			}
			if(end!=null){
				pramList.add(end);
			}
			
			return (List<CgTreatise>)getHibernateTemplate().find(builder.toString(), pramList.toArray());
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
//专著分页查询
	public QueryResult<CgTreatise> nfindByProperty(String propertyName, List value,Date begin,Date end,int firstindex,int maxresult) {
		log.debug("finding CgTreatise instance with property: " + propertyName
				+ ", value: " + value.toString());
		
		try {
			QueryResult<CgTreatise> queryResult=new QueryResult<CgTreatise>();
			
			StringBuffer queryStr=new StringBuffer();
			queryStr.append("from CgTreatise as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.publishDate>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.publishDate<:end");
			}
			Query query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(query.getQueryString().indexOf(" and model.publishDate>=:begin")!=-1){
				query.setParameter("begin", begin);
			}
			if(query.getQueryString().indexOf(" and model.publishDate<:end")!=-1){
				query.setParameter("end", end);
			}
			if(firstindex!=-1&&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			queryResult.setResultlist(query.list());
			queryStr.delete(0,queryStr.length());//清除之前的字符窜
			queryStr.append("select count(*) from CgTreatise as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.publishDate>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.publishDate<:end");
			}
			query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(query.getQueryString().indexOf(" and model.publishDate>=:begin")!=-1){
				query.setParameter("begin", begin);
			}
			if(query.getQueryString().indexOf(" and model.publishDate<:end")!=-1){
				query.setParameter("end", end);
			}
			queryResult.setTotalrecord((Long)query.uniqueResult());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	
	public QueryResult<CgTreatise> findByTreatiseId(Object treatiseId,int firstindex,int maxresult) {
		return findByProperty(TREATISE_ID, treatiseId, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByTeacherId(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByTeacherId(Object teacherId,int firstindex,int maxresult) {
		return findByProperty(TEACHER_ID, teacherId, firstindex, maxresult);
	}
	public QueryResult<CgTreatise> findByTeacherId(Object teacherId) {
		return findByProperty(TEACHER_ID, teacherId,-1,-1);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByTreatiseTitle(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByTreatiseTitle(Object treatiseTitle,int firstindex,int maxresult) {
		return findByProperty(TREATISE_TITLE, treatiseTitle, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByPublishAdress(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByPublishAdress(Object publishAdress,int firstindex,int maxresult) {
		return findByProperty(PUBLISH_ADRESS, publishAdress, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByPublishDw(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByPublishDw(Object publishDw,int firstindex,int maxresult) {
		return findByProperty(PUBLISH_DW, publishDw, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByTreatiseType(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByTreatiseType(Object treatiseType,int firstindex,int maxresult) {
		return findByProperty(TREATISE_TYPE, treatiseType, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByZiShu(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByZiShu(Object ziShu,int firstindex,int maxresult) {
		return findByProperty(ZI_SHU, ziShu, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByLanguage(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByLanguage(Object language,int firstindex,int maxresult) {
		return findByProperty(LANGUAGE, language, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByYiWen(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByYiWen(Object yiWen,int firstindex,int maxresult) {
		return findByProperty(YI_WEN, yiWen, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByXueKe(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByXueKe(Object xueKe,int firstindex,int maxresult) {
		return findByProperty(XUE_KE, xueKe, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findBySchoolSign(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findBySchoolSign(Object schoolSign,int firstindex,int maxresult) {
		return findByProperty(SCHOOL_SIGN, schoolSign, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByIsbn(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByIsbn(Object isbn,int firstindex,int maxresult) {
		return findByProperty(ISBN, isbn, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByKeYanFen(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByKeYanFen(Object keYanFen,int firstindex,int maxresult) {
		return findByProperty(KE_YAN_FEN, keYanFen, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findByComment(java.lang.Object)
	 */
	public QueryResult<CgTreatise> findByComment(Object comment,int firstindex,int maxresult) {
		return findByProperty(COMMENT, comment, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#findAll()
	 */
	public QueryResult<CgTreatise> findAll(int firstindex,int maxresult) {
		log.debug("finding all CgTreatise instances");
		try {
			QueryResult<CgTreatise> queryResult=new QueryResult<CgTreatise>();
			String queryString = "from CgTreatise cgTrestise";
			Query query=getSessionFactory().getCurrentSession().createQuery(queryString);
			if(firstindex!=-1&&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			queryResult.setResultlist(query.list());
			query=getSessionFactory().getCurrentSession().createQuery("select count(*) from CgTreatise cgTrestise");
			queryResult.setTotalrecord((Long)query.uniqueResult());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#merge(com.gdpu.project.vo.CgTreatise)
	 */
	public CgTreatise merge(CgTreatise detachedInstance) {
		log.debug("merging CgTreatise instance");
		try {
			CgTreatise result = (CgTreatise) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#attachDirty(com.gdpu.project.vo.CgTreatise)
	 */
	public void attachDirty(CgTreatise instance) {
		log.debug("attaching dirty CgTreatise instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgTreatiseDao#attachClean(com.gdpu.project.vo.CgTreatise)
	 */
	public void attachClean(CgTreatise instance) {
		log.debug("attaching clean CgTreatise instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static CgTreatiseDao getFromApplicationContext(ApplicationContext ctx) {
		return (CgTreatiseDao) ctx.getBean("CgTreatiseDAO");
	}

	public int count(String teacherId) {
		String hql="from CgTreatise as c where c.teacherId=?";
		int count=0;
		List<CgTreatise> list=(List<CgTreatise>)getHibernateTemplate().find(hql, teacherId);
		Iterator<CgTreatise> it=list.iterator();
		while(it.hasNext())
		{
			CgTreatise c=it.next();
			if(c.getKeYanFen()==0f){
				count=count+0;
			}else{
				count=count+(int)c.getKeYanFen();
			}
		}
		return count;
	}

}
